﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EM.Repository.utility;
using System.Data.SqlClient;
using System.Data;

namespace EM.operation.expense
{
    public partial class default_edit : System.Web.UI.Page
    {
        string sTask = "";
        public int EXPENSEID = 0;
        FillCombo Fc = new FillCombo();
        Conversion oC = new Conversion();
        protected void Page_Load(object sender, EventArgs e)
        {
            Authentication ua = new Authentication();
            ua.CheckRolePageAuthentication(17, Authentication.RedirectionURLTypes.TimeOutPage);

            sTask = Request.QueryString["task"].ToString();
            Int32.TryParse(Request.QueryString["ID"], out EXPENSEID);


            if (sTask == "Delete")
            {
                lblSave.Text = "Sil";
            }

            if (!IsPostBack)
            {


                if (sTask == "Insert")
                {
                    Fc.User(ddlExpenseUser, "0", true, Convert.ToInt32(Session["WORKGROUPID"]));
                    Fc.LookUpValue(ddlExpensePaymentType, "", true, "EXPENSE_PAYMENT_TYPE", "TR");
                    Fc.ExpenseType(ddlExpenseType, 0, true, Convert.ToInt32(Session["WORKGROUPID"]));
                    Fc.Currency(ddlCurrencyId, "1", true);

                }

                if (sTask == "Update" || sTask == "Delete")
                {
                    GetData();


                }
            }
        }

        private void GetData()
        {

            DbHelper srv = new DbHelper();
            SqlCommand cmd = new SqlCommand();

            string sSQL = @" SELECT EXPENSEID, EXPENSETYPEID, ENTITYID, AMOUNT, INSTALLMENTSTARTDATE, EXPENSEUSERID, CURRENCYID,
                            INSTALLMENTCOUNT, EXPENSEPAYMENTTYPE, DESCRIPTION, EXPENSEDATE FROM TBLEXPENSE 
                            WHERE EXPENSEID = @EXPENSEID";
            cmd.CommandText = sSQL;
            cmd.Parameters.Add("EXPENSEID", SqlDbType.Int).Value = EXPENSEID;
            DataTable dt = srv.GetDataTable(cmd, "");

            if (dt.Rows.Count > 0)
            {
                Fc.User(ddlExpenseUser, dt.Rows[0]["EXPENSEUSERID"].ToString(), true, Convert.ToInt32(Session["WORKGROUPID"]));
                Fc.ExpenseType(ddlExpenseType, Convert.ToInt32(dt.Rows[0]["EXPENSETYPEID"]), true, Convert.ToInt32(Session["WORKGROUPID"]));
                lblExpenseId.Text = dt.Rows[0]["EXPENSEID"].ToString();
                rdpDate.SelectedDate = Convert.ToDateTime(dt.Rows[0]["EXPENSEDATE"]);
                Fc.LookUpValue(ddlExpensePaymentType, dt.Rows[0]["EXPENSEPAYMENTTYPE"].ToString(), true, "EXPENSE_PAYMENT_TYPE", Session["LANGCODE"].ToString());
                ddlExpensePaymentType_SelectedIndexChanged(null, null);
                if (dt.Rows[0]["ENTITYID"].ToString() != "")
                    ddlEntity.SelectedValue = dt.Rows[0]["ENTITYID"].ToString();
                if (dt.Rows[0]["INSTALLMENTSTARTDATE"].ToString() != "")
                    rdpInstallmentStartDate.SelectedDate = Convert.ToDateTime(dt.Rows[0]["INSTALLMENTSTARTDATE"]);
                txtAmount.Text = oC.CNumS2C(Convert.ToDouble(dt.Rows[0]["AMOUNT"]));
                txtInstalmentCount.Text = dt.Rows[0]["INSTALLMENTCOUNT"].ToString();
                txtDescription.Text = dt.Rows[0]["DESCRIPTION"].ToString();
                Fc.Currency(ddlCurrencyId, dt.Rows[0]["CURRENCYID"].ToString(), true);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            DbHelper srv = new DbHelper();
            SqlCommand cmd = new SqlCommand();

            string sSQL = "";

            if (sTask == "Insert")
            {
                sSQL = @" DECLARE @UID INT;
                           INSERT INTO TBLEXPENSE
                            (EXPENSETYPEID,ENTITYID,AMOUNT,INSTALLMENTCOUNT,EXPENSEPAYMENTTYPE,DESCRIPTION,EXPENSEDATE,CREUSERID,CREDATE,MODUSERID,MODDATE,INSTALLMENTSTARTDATE, EXPENSEUSERID, INSTALLMENTFLG, CURRENCYID, BRANCHID, WORKGROUPID)
                            SELECT @EXPENSETYPEID,@ENTITYID,@AMOUNT,@INSTALLMENTCOUNT,@EXPENSEPAYMENTTYPE,@DESCRIPTION,@EXPENSEDATE,@CREUSERID,GETDATE(),@CREUSERID,GETDATE(),@INSTALLMENTSTARTDATE,@EXPENSEUSERID, @INSTALLMENTFLG, @CURRENCYID, @BRANCHID, @WORKGROUPID

                          SET @UID = SCOPE_IDENTITY();

                          IF @EXPENSEPAYMENTTYPE = 'CC' AND @INSTALLMENTCOUNT <> 0 AND @INSTALLMENTSTARTDATE IS NOT NULL
                          BEGIN
                                EXEC dbo.spCreateInstallmentDetail @UID;
                          END

                            SELECT @UID;";



            }
            else if (sTask == "Update")
            {
                sSQL = @"UPDATE TBLEXPENSE SET
                        EXPENSETYPEID = @EXPENSETYPEID,
                        ENTITYID = @ENTITYID,
                        AMOUNT= @AMOUNT,
                        INSTALLMENTCOUNT= @INSTALLMENTCOUNT,
                        EXPENSEPAYMENTTYPE= @EXPENSEPAYMENTTYPE,
                        DESCRIPTION= @DESCRIPTION,
                        EXPENSEDATE= @EXPENSEDATE,
                        MODUSERID= @CREUSERID,
                        MODDATE = GETDATE(),
                        EXPENSEUSERID = @EXPENSEUSERID,
                        INSTALLMENTSTARTDATE = @INSTALLMENTSTARTDATE,
                        INSTALLMENTFLG = @INSTALLMENTFLG,
                        CURRENCYID = @CURRENCYID,
                        BRANCHID = @BRANCHID
                        WHERE EXPENSEID = @EXPENSEID 

                        IF @EXPENSEPAYMENTTYPE = 'CC' AND @INSTALLMENTCOUNT <> 0 AND @INSTALLMENTSTARTDATE IS NOT NULL
                        BEGIN
                                DELETE FROM TBLINSTALLMENT WHERE EXPENSEID = @EXPENSEID
                                EXEC dbo.spCreateInstallmentDetail @EXPENSEID;
                        END ";
            }
            else if (sTask == "Delete")
            {
                sSQL = @"DELETE FROM TBLINSTALLMENT  WHERE EXPENSEID = @EXPENSEID
                        DELETE FROM TBLEXPENSE WHERE EXPENSEID = @EXPENSEID ";
            }

            cmd.CommandText = sSQL;

            if ((bool)HttpContext.Current.Session["UserIsAnAdmin"])
                cmd.Parameters.AddWithValue("@EXPENSEUSERID", ddlExpenseUser.SelectedValue);
            else
                cmd.Parameters.AddWithValue("@EXPENSEUSERID", Session["USERID"]);

            cmd.Parameters.AddWithValue("@EXPENSEID", EXPENSEID);
            cmd.Parameters.AddWithValue("@CREUSERID", Session["USERID"]);
            cmd.Parameters.AddWithValue("@BRANCHID", Session["BRANCHID"]);
            cmd.Parameters.AddWithValue("@EXPENSEDATE", rdpDate.SelectedDate);
            cmd.Parameters.AddWithValue("@DESCRIPTION", txtDescription.Text);
            cmd.Parameters.AddWithValue("@EXPENSEPAYMENTTYPE", ddlExpensePaymentType.SelectedValue);
            cmd.Parameters.AddWithValue("@CURRENCYID", ddlCurrencyId.SelectedValue);
            cmd.Parameters.AddWithValue("@WORKGROUPID", Session["WORKGROUPID"]);
            cmd.Parameters.AddWithValue("@AMOUNT", oC.CNumC2S(txtAmount.Text));
            if (ddlEntity.SelectedValue != "" && ddlEntity.SelectedValue != "0")
                cmd.Parameters.AddWithValue("@ENTITYID", ddlEntity.SelectedValue);
            else
                cmd.Parameters.AddWithValue("@ENTITYID", DBNull.Value);
            cmd.Parameters.AddWithValue("@EXPENSETYPEID", ddlExpenseType.SelectedValue);

            if (chkInstallmentFlg.Checked)
            {
                if (rdpInstallmentStartDate.SelectedDate != rdpInstallmentStartDate.MinDate)
                    cmd.Parameters.AddWithValue("@INSTALLMENTSTARTDATE", rdpInstallmentStartDate.SelectedDate);
                else
                    cmd.Parameters.AddWithValue("@INSTALLMENTSTARTDATE", DBNull.Value);

                if (txtInstalmentCount.Text != "")
                    cmd.Parameters.AddWithValue("@INSTALLMENTCOUNT", txtInstalmentCount.Text);
                else
                    cmd.Parameters.AddWithValue("@INSTALLMENTCOUNT", DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@INSTALLMENTSTARTDATE", DBNull.Value);
                cmd.Parameters.AddWithValue("@INSTALLMENTCOUNT", DBNull.Value);
            }

            cmd.Parameters.AddWithValue("@INSTALLMENTFLG", chkInstallmentFlg.Checked ? "Y" : "N");

            DataTable dt = srv.GetDataTable(cmd, "");

            if (sTask == "Insert")
            {
                if (srv.GetGlobalDefaultValue("ENABLE_EXPENSE_NOTIFICATION") == "Y")
                {
                    Notice nc = new Notice();
                    nc.ExpenseNotification(Convert.ToInt32(dt.Rows[0][0]), Convert.ToInt32(Session["WORKGROUPID"]));

                }
            }

            string strScript = "window.opener['rgMaster'].AjaxRequest('rgMaster', 'Rebind'); window.close();";
            ClientScript.RegisterStartupScript(typeof(string), "", strScript.ToString(), true);
        }

        protected void ddlExpensePaymentType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlExpensePaymentType.SelectedValue == "CC")
            {
                Fc.CreditCard(ddlEntity, 0, true, 0, Convert.ToInt32(Session["WORKGROUPID"]));
                rfvEntity.ValidationGroup = "vg";
            }
            else if (ddlExpensePaymentType.SelectedValue == "BT")
            {
                Fc.BankAccount(ddlEntity, 0, true, 0, Convert.ToInt32(Session["WORKGROUPID"]));
                rfvEntity.ValidationGroup = "vg";
            }
            else
            {
                rfvEntity.ValidationGroup = "vg_fake";
            }
        }

        protected void chkInstallmentFlg_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInstallmentFlg.Checked)
            {
                txtInstalmentCount.Enabled = true;
                txtInstalmentCount.CssClass = "editinputrq";
                rdpInstallmentStartDate.Enabled = true;
                rfvInstallmentStartDate.CssClass = "editinputrq";
                rfvInstalmentCount.ValidationGroup = "vg";
                rfvInstallmentStartDate.ValidationGroup = "vg";
            }
            else
            {
                txtInstalmentCount.Enabled = false;
                rdpInstallmentStartDate.Enabled = false;
                rfvInstalmentCount.ValidationGroup = "vg_fake";
                rfvInstallmentStartDate.ValidationGroup = "vg_fake";
                txtInstalmentCount.CssClass = "editinput";
                rfvInstallmentStartDate.CssClass = "editinput";
            }
        }
    }
}